<?php
//ini_set('display_errors', 1);            //错误信息
//ini_set('display_startup_errors', 1);    //php启动错误信息
//error_reporting(-1);                    //打印出所有的 错误信息
header("Content-Type:text/html; charset=utf-8");
date_default_timezone_set('PRC');
$database = include "./data/conf/database.php";
$conn = mysqli_connect($database['hostname'], $database['username'], $database['password']);
mysqli_select_db($conn, $database['database']);

$host = $database['hostname'];
$dbName = $database['database'];
$user = $database['username'];
$pass = $database['password'];
$dsn = "mysql:host=$host;dbname=$dbName";
$pdo = new PDO($dsn, $user, $pass);
/**
 * 确保文件夹存在并可写
 * @param $dir  绝对路径$_SERVER['DOCUMENT_ROOT']
 */
function ensure_writable_dir($dir)
{
    $dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
    if (!is_dir($dir)) {
        mkdir($dir . '/', 0777, true);
    }
}

function download($url, $path)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $resource = fopen($_SERVER['DOCUMENT_ROOT'] . $path, 'a');
    fwrite($resource, $file);
    fclose($resource);
}

function randomkeys($length)
{
    //$pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    $str = null;
    $strPol = "1234567890"; //大小写字母以及数字
    $max = strlen($strPol) - 1;
    for ($i = 0; $i < $length; $i++) {
        $str .= $strPol[rand(0, $max)];
    }
    return $str;
}

function randomsku($length)
{
    $key = '';
    $pattern = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLOMNOPQRSTUVWXYZ';
    for ($i = 0; $i < $length; $i++) {
        $key .= $pattern{mt_rand(0, 35)}; //生成php随机数

    }
    return $key;
}

function trimd($str)
{
    $str = str_replace("\t", " ", $str);
//    $str = str_replace("'", "''", $str);
    $str = str_replace('V', "", $str);
    $str = str_replace("\r", "", $str);
    $str = str_replace("$", "", $str);
    $str = str_replace("\n", "<br/>", $str);
    return trim($str);
}

function rpa($str)
{
    return substr($str, 0, strlen($str) - 1);
}

/**
 * 检测数据表是否存在
 * @param string $table
 * @return bool
 */
function checkTableExist($table, $database, $pdo)
{
    $sql = sprintf("SELECT COUNT(1) FROM `INFORMATION_SCHEMA`.`TABLES` WHERE `TABLE_SCHEMA`='%s' AND `TABLE_NAME` = '%s'", $database['database'], $table);
    $result = $pdo->query($sql);
    if ($result === false) {//表不存在
        return false;
    }
    if (!$result->fetchColumn(0)) {
        return false;
    }
    return true;
}

/**
 * 复制表结构
 * @param string $table
 * @param string $newTable
 * @param string $company_id
 * @return bool
 */
function copyTable($table = '', $newTable = '', $company_id = '', $pdo)
{
    $sql = sprintf("create table %s like %s", $newTable, $table);
    $result = $pdo->query($sql);
    if ($result === false) {
        return false;
    }
    $sql = sprintf("alter table %s comment '%s'", $newTable, '公司-' . $company_id . "_" . $table . '分表');
    $pdo->query($sql);
    return true;
}

/**
 * GUID的生成源码
 * *代码中//后面标示了字符的转码如chr(45)代表“-”，chr(123)代表“{”等等，可以根据自己需要改写生成GUID的位数以及样式
 * @return string   26E69265-078C-C7D9-A0CA-33348CEEE712
 */

function guid()
{
    if (function_exists('com_create_guid')) {
        return com_create_guid();
    } else {
        mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45);// "-"
        $uuid = substr($charid, 0, 8) . $hyphen
            . substr($charid, 8, 4) . $hyphen
            . substr($charid, 12, 4) . $hyphen
            . substr($charid, 16, 4) . $hyphen
            . substr($charid, 20, 12);
        return strtolower($uuid);
    }
}

function ww($content)
{
    $file = $_SERVER['DOCUMENT_ROOT'] . "/ww.log";
    file_put_contents($file, "\r\n********************** " . date('Y-m-d H:i:s', time()) . " **********************************\r\n", FILE_APPEND);
    file_put_contents($file, $content, FILE_APPEND);
}

// $myfile = fopen("webdictionary.txt", "r") or die("Unable to open file!");
// $maindata=fread($myfile,filesize("webdictionary.txt"));
// fclose($myfile);
//$myfile = fopen("newfile.txt", "w") or die("Unable to open file!");
//fwrite($myfile, $_POST["data"]);
//fclose($myfile);
$data = json_decode($_POST["data"], true);
//$data = json_decode($maindata, true);
$user = trimd($_GET["username"]);

$pwd = trimd($_GET["password"]);
//$user="djfadmin";
//echo $user."<br/>";
$Platform = $data['Platform'];
//echo $Platform."<br/>";
$Category = trimd($data['Category']);
//echo $Category."<br/>";
$Url = trimd($data['Url']);
//echo $Url."<br/>";
$Proname = trimd($data['Proname']);
//echo $Proname."<br/>";
$Price = htmlspecialchars($data['Price']);
//echo $Price."<br/>";
$Currency = $data['Currency'];
//echo $Currency."<br/>";
$Shopname = trimd($data['Shopname']);
//echo $Shopname."<br/>";
$Sketch = trimd($data['Sketch']);
//echo $Sketch."<br/>";
$Description = trimd($data['Description']);
if (empty($Description)) {
    $Description = $Sketch;
}
//echo $Description."<br/>";
//$PID = $data['PID'];
//echo $PID."<br/>";
$Images = $data['Images'];
$Attribute = $data['Attribute'];
$Products = $data['Products'];
if (!empty($Sketch)) {
    $content = $Sketch;
}
if (!empty($Description)) {
    $content = $Description;
}
$ucalist = "select * from ean_user where username='" . $user . "' AND password = '" . $pwd . "'";

$ucaresult = mysqli_query($conn, $ucalist);
if (mysqli_num_rows($ucaresult) < 1) {
    echo "user not exist!";
    exit;
}
$userInfo = mysqli_fetch_array($ucaresult);

//产品表
$productTbale = 'ean_products';
$newProductTable = $productTbale . "_" . $userInfo['company_id'];

//产品图表
$productImgTbale = 'ean_img';
$newProductImgTbale = $productImgTbale . "_" . $userInfo['company_id'];
//属性表
$propertyTbale = 'ean_shuxing';
$newPropertyTbale = $propertyTbale . "_" . $userInfo['company_id'];

//公司分表不存在
if (checkTableExist($newProductTable, $database, $pdo) == false) {
    copyTable($productTbale, $newProductTable, $userInfo['company_id'], $pdo);
}
if (checkTableExist($newProductImgTbale, $database, $pdo) == false) {
    copyTable($productImgTbale, $newProductImgTbale, $userInfo['company_id'], $pdo);
}
if (checkTableExist($newPropertyTbale, $database, $pdo) == false) {
    copyTable($propertyTbale, $newPropertyTbale, $userInfo['company_id'], $pdo);
}

$calist = "select * from ean_bcategory where bname='" . $Category . "' and platform='" . $Platform . "' and user_name='" . $user . "'";
$caresult = $pdo->query($calist);
if (($caresult->fetchColumn(0)) == 0) {
    $sqlca = "INSERT INTO ean_bcategory(bname,platform,user_name)VALUES('" . $Category . "','" . $Platform . "','" . $user . "')";
    mysqli_query($conn, $sqlca);
}
$Arrtsname = array();
foreach ($Attribute as $key => $Value) {
    array_push($Arrtsname, $key);
}
if (count($Arrtsname) > 1) {
    $shuxing = "ColorSize";
} else {
    $shuxing = $Arrtsname[0];
}

$guid = guid();


$sql = "INSERT INTO " . $newProductTable . "(proname,price,saleprice,skucode,coin,code,content,ndate,bname,user_name,des,keywords,weight,kucun,btname,fromurl,shopname,platform,sketch,guid,timestamp)VALUES('" . $Proname . "','" . $Price . "','" . $Price . "','" . randomsku(19) . "','" . $Currency . "','" . randomkeys(13) . "','" . trimd($content) . "','" . date("Y-m-d", time()) . "','" . $Category . "','" . $user . "','" . $Description . "','','1','50','" . trimd($shuxing) . "','" . $Url . "','" . $Shopname . "','" . $Platform . "','" . $Sketch . "','" . $guid . "','" . time() . "')";
mysqli_query($conn, $sql);

if (!empty($Products[0]["Image"])) {
    for ($p = 0; $p < count($Products[0]["Image"]); $p++) {
        $path = '/public/uploads/product/' . $userInfo['company_id'] . "/" . date("Y-m-d", time()) . "/";
        ensure_writable_dir($path);
        $pathImg1 = '';
        $pathImg1 = $path . randomkeys(8) . strtotime(date("Y-m-d H:i:s", time())) . ".jpg";
        download($Products[0]["Image"][$p], $pathImg1);
        mysqli_query($conn, "INSERT INTO " . $newProductImgTbale . "(imgpath,guid,px,serial)VALUES('" . $pathImg1 . "','" . $guid . "','" . $p . "',0);");
    }
}
for ($i = 0; $i < count($Products); $i++) {
    $sx = "";
    for ($r = 0; $r < count($Products[$i]["Value"]); $r++) {
        $sx .= $Products[$i]["Value"][$r] . ",";
    }
    $serial = ($i + 1);
    mysqli_query($conn, "INSERT INTO " . $newPropertyTbale . "(serial,cname,guid,price,saleprice,kucun,skucode)VALUES('" . $serial . "','" . trimd(rpa($sx)) . "','" . $guid . "','" . trimd($Products[$i]["Price"]) . "','" . trimd($Products[$i]["Price"]) . "','50','');");
    //$btid = mysqli_insert_id();
    if (!empty($Products[$i]["Image"])) {
        for ($t = 0; $t < count($Products[$i]["Image"]); $t++) {
            $path = '/public/uploads/product/' . $userInfo['company_id'] . "/" . date("Y-m-d", time()) . "/";
            ensure_writable_dir($path);
            $pathImg2 = '';
            $pathImg2 = $path . randomkeys(8) . strtotime(date("Y-m-d H:i:s", time())) . ".jpg";
            download($Products[$i]["Image"][$t], $pathImg2);
            ww($t);
            mysqli_query($conn, "INSERT INTO " . $newProductImgTbale . "(imgpath,guid,px,serial)VALUES('" . $pathImg2 . "','" . $guid . "','" . ($t + 1) . "','" . $serial . "');");
        }
    }
}
for ($i = 0; $i < count($Images); $i++) {
    $path = '/public/uploads/product/' . $userInfo['company_id'] . "/" . date("Y-m-d", time()) . "/";
    ensure_writable_dir($path);
    $pathImg3 = '';
    $pathImg3 = $path . randomkeys(8) . strtotime(date("Y-m-d H:i:s", time())) . ".jpg";
    download($Images[$i], $pathImg3);
    mysqli_query($conn, "INSERT INTO " . $newProductImgTbale . "(`imgpath`,`guid`,`px`,`serial`)VALUES('" . $pathImg3 . "','" . $guid . "','" . $i . "',0);");
}
echo "Upload Success!";

?>
